package com.jinghua.treatment.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.jinghua.treatment.common.GlobalConstant;
import com.jinghua.treatment.common.controller.BaseController;
import com.jinghua.treatment.common.domain.JSONResult;
import com.jinghua.treatment.common.exception.BizException;
import com.jinghua.treatment.entity.SysDoctor;
import com.jinghua.treatment.entity.SysPatient;
import com.jinghua.treatment.service.SysDoctorService;
import com.jinghua.treatment.service.SysPatientService;
import com.jinghua.treatment.tools.IDGenerator;
import com.jinghua.treatment.tools.PropertyUtil;
import com.jinghua.treatment.tools.StringUtil;
import com.jinghua.treatment.wechat.biz.SMSBiz;
import com.jinghua.treatment.wechat.biz.WechatBiz;
import com.jinghua.treatment.wechat.entity.WXJSConfig;
import com.jinghua.treatment.wechat.util.HttpUtil;
import com.jinghua.treatment.wechat.util.WechatUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Controller
@RequestMapping("/wechat")
public class WechatController extends BaseController{

    Logger log = LogManager.getLogger(WechatController.class);

    @Autowired
    private WechatBiz textBiz ;

    @Autowired
    private  SysDoctorService sysDoctorService;

    @Autowired
    private SysPatientService sysPatientService;

    @ApiOperation(value="微信公众平台认证")
    @RequestMapping(value="/gateway")
    @ResponseBody
    public String gateway(HttpServletRequest request,HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(request.getInputStream());
            textBiz.doBussiness(document,request,response);
        } catch (DocumentException e) {
            e.printStackTrace();
            try {
                response.getWriter().write("parse xml error!");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

        //微信服务器认证
      /*  String str =  request.getParameter("echostr");
        return str;*/
    }

    @ApiOperation(value="微信公众平台获取js-sdk验证信息")
    @RequestMapping(value="/jsconfig")
    @ResponseBody
    public JSONResult jsconfig(HttpServletRequest request,HttpServletResponse response,String vurl){
        response.setCharacterEncoding("UTF-8");
        WXJSConfig  wxjsConfig = (WXJSConfig)session.getServletContext().getAttribute("wxjsConfig");

        if(wxjsConfig==null||!wxjsConfig.isTicketValid()){
            wxjsConfig = new WXJSConfig();
            wxjsConfig.setAppId(PropertyUtil.getConfig("wechat.appId"));
            wxjsConfig.setTimestamp(new Date().getTime()/1000);
            wxjsConfig.setNonceStr(IDGenerator.uuid().substring(0,16));
            String access_token  = WechatUtil.getAccessToken();
            System.out.println("access_token:"+access_token);
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
            String result  = HttpUtil.sendGetRequest(url,null);
            JSONObject jsonObject = JSONObject.parseObject(result);
            wxjsConfig.setJsapi_ticket(jsonObject.getString("ticket"));
            wxjsConfig.setTicketTime(new Date());
            System.out.println("vurl:"+vurl);
            String sign =  WechatUtil.wxSign(wxjsConfig,vurl);
            wxjsConfig.setSignature(sign);
            session.getServletContext().setAttribute("wxjsConfig",wxjsConfig);
        }
        return jsonResult(GlobalConstant.SUCCESS_CODE,"ok",wxjsConfig);
    }

    @ApiOperation(value="微信公众平台用户授权回调")
    @RequestMapping(value="/userauth")
    public String userauth(String  code,String state,Model model){
       if(code!=null){//用code 换access_token
            String url ="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+PropertyUtil.getConfig("wechat.appId")+"&secret="+PropertyUtil.getConfig("wechat.secret")+"&code="+code+"&grant_type=authorization_code";
            String json = HttpUtil.sendGetRequest(url,null);
            log.debug("json:"+json);
            JSONObject jsonObject=  JSONObject.parseObject(json);
           if(jsonObject!=null&&jsonObject.get("access_token")!=null){
              // String userLink = "https://api.weixin.qq.com/sns/userinfo?access_token="+jsonObject.get("access_token")+"&openid=OPENID&lang=zh_CN"
               String openid = (String)jsonObject.get("openid");
               if("zxzy".equals(state)){//在线中医咨询
                   SysPatient sysPatient = sysPatientService.selectByWechat(openid);
                   if(sysPatient!=null)
                       model.addAttribute("link","/mod-page/patient/my_doctor_list.html?patientId="+sysPatient.getPatientId());
                   else
                       model.addAttribute("link","/mod-page/patient/patient_regist.html");
               }else if("wdbl".equals(state)){//我的病例
                   SysPatient sysPatient = sysPatientService.selectByWechat(openid);
                   if(sysPatient!=null)
                       model.addAttribute("link","/mod-page/patient/patient_center.html?patientId="+sysPatient.getPatientId());
                   else
                       model.addAttribute("link","/mod-page/patient/patient_regist.html");
               }else if("fswzd".equals(state)){//用户点击 医生发送的问诊单
                        String doctorId = request.getParameter("doctorId");
                        String inquiryId = request.getParameter("inquiryId");
                        SysPatient sysPatient  =  sysPatientService.selectByWechat(openid);
                        //情况一 用户已经注册，且关注了医生，直接跳转到问诊单页面
                       if(sysPatient!=null&&sysDoctorService.isMyPatient(Integer.parseInt(doctorId),sysPatient.getPatientId())){
                           model.addAttribute("link","/mod-page/inquiry/inquiry-for-send.html?pid="+sysPatient.getPatientId()+"&inquiryId="+inquiryId+"&did="+doctorId);
                       }else{ //情况二 用户没有注册，先跳转到医生关注页面
                           model.addAttribute("link","/mod-page/studio/add_patient.html?patientId="+sysPatient.getPatientId());
                       }
               }else if("sharedoctor".equals(state)){//分享医生二维码
                   System.out.println("openid:"+openid);
                   SysPatient sysPatient = sysPatientService.selectByWechat(openid);
                   System.out.println("sysPatient:"+sysPatient);
                   String doctorId = request.getParameter("doctorId");
                   if(sysPatient!=null)
                       model.addAttribute("link","/mod-page/patient/my_doctor_detail.html?patientId="+sysPatient.getPatientId()+"&doctorId="+doctorId+"&tag=doctorInfo");
                   else{
                       model.addAttribute("link","/d/doctor/followDoctor?doctorId="+doctorId);
                   }

               }
           }
       }
        return "common/redirect";
    }

}
